import moment from "moment";
import html2canvas from 'html2canvas'
import JSPDF from 'jspdf'
import $store from '@/store/index.js'
import {h, reactive} from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus'
/************************************* localStorage *************************************/
/*
 * 存储localStorage
 */
export const SetLocalStorage = (name, content) => {
    if (!name) return;
    if (typeof content !== 'string') {
        content = JSON.stringify(content);
    }
    window.localStorage.setItem(name, content);
}

/**
 * 获取localStorage
 */
export const GetLocalStorage = name => {
    if (!name) return;
    return window.localStorage.getItem(name);
}

/**
 * 删除localStorage
 */
export const RemoveLocalStorage = name => {
    if (!name) return;
    window.localStorage.removeItem(name);
}
/**
 * 清除localStorage
 */
export const ClearLocalStorage = () => {
    window.localStorage.clear();
}
/************************************* 统一提示弹窗 *************************************/

export const MessageBox = (text = '是否继续?', title = '提示', type = 'warning') => {
    return ElMessageBox.confirm(text, title, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: type
    });
}

export const MessageSuccess = (text = '操作成功') => {
    return ElMessage.success({
        message: text
    });
}

export const MessageError = (text = '操作失败') => {
    return ElMessage.error({
        message: text
    });;
}
export const MessageInfo = (text = '操作信息') => {
    return ElMessage.info({
        message: text
    });;
}
/************************************* 时间格式化 *************************************/
export function FormatDate(time) {
    if (time == 0 || time == null || time == "")
        return '----';
    return moment(time)
        .locale("zh-cn")
        .format("YYYY-MM-DD");
}
export function FormatDateTime(time, f) {
    if (time == 0 || time == null || time == "")
        return '';
    return moment(time)
        .locale("zh-cn")
        .format(f || "YYYY-MM-DD HH:mm:ss");
}
/************************************* 文件 *************************************/

//传入文件的filepath,比如:220803/29d718c2-dff9-49f6-a096-4804a4c602fc.pdf
//如果是pdf/图片,那么直接在浏览器显示,如果是其他的文件类型,那么下载
export const preOrDownFile = (filepath) => {
    const url = window.REQUEST_URL + "/attachment/preview/" + filepath;
    let openType = "_self"
    if (filepath.toLowerCase().endsWith('pdf') ||
        filepath.toLowerCase().endsWith('png') ||
        filepath.toLowerCase().endsWith('jpg') ||
        filepath.toLowerCase().endsWith('gif') ||
        filepath.toLowerCase().endsWith('jpeg')) {
        openType = "_blank"
    }
    window.open(url, openType,
        'top=0,toolbar=no, menubar=no, scrollbars=no, location=no, status=no')
}
/************************************* 业务  *************************************/
/**
 * 获取隐患状态
 * @param {状态值} val 
 * val默认0待开票，1已开票，2完成
 */
export const GetDangerState = (val) => {
    let result = {
        state: "0",
        text: '待整改',
        color: 'bg-unknown'
    }
    switch (val) {
        case "0":
            result = {
                state: "0",
                text: '待整改',
                color: 'bg-unknown'
            }
            break;
        case "1":
            result = {
                state: "1",
                text: '已整改',
                color: 'bg-primary'
            }
            break;
        case "2":
            result = {
                state: 2,
                text: '已验收',
                color: 'bg-sucess'
            }
            break
    }
    return result;
}
/**
 * 获取危险作业级别
 * @param {状态值} val 
 * 
 */
export const GetLevelText = (val) => {
    let text = ""
    switch (val) {
        case "1":
            text = "一级";
            break;
        case "2":
            text = "二级";
            break;
        case "3":
            text = "三级";
            break;
        case "3":
            text = "四级";
            break;
        default:
            text = "未知"
            break;
    }
    return text;
}
/************************************* 常用工具 *************************************/
// 深拷贝函数
export function deepClone(source) {
    if (!source) {
        return source
    }
    // .constructor指向该对象的构造函数
    const targetObj = source.constructor === Array ? [] : {};
    // 遍历对象或数组
    for (let key in source) {
        // obj.hasOwnProperty() 指示对象自身属性中是否具有指定的属性
        if (source.hasOwnProperty(key)) {
            // 判断自身属性是否存在，且是否为对象,是对象进一步遍历，非对象直接赋值，不存在属性不执行
            if (source[key] && typeof (source[key]) === 'object') {
                // 维护层代码 进一步判断source[key] 运行代码可去除
                targetObj[key] = source[key].constructor === Array ? [] : {}
                // 递归
                targetObj[key] = deepClone(source[key])
            } else {
                // source[key]不是对象时直接赋值
                targetObj[key] = source[key]
            }
        }
    }
    return targetObj
}
//生成uuid
export function guid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0,
            v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}
//动态生成路由
export function mapPermissionToRoutes(allRoutes, permission, isAdmin) {
    let permissionList = permission.flat();
    let routeResult = []
    allRoutes.forEach(route => {
        if (permissionList.includes(route.name) || isAdmin) {
            routeResult.push(route);
        }
    });
    return routeResult;
}
//动态生成菜单
export function mapPermissionToMenus(allMenus, permission, isAdmin) {
    let permissionList = permission.flat();
    function deepFirstChange(allMenus) { //把source的每一项，改改字段，然后添加到target里去
        let res = allMenus.map(item => {
            let changedChildren = []
            if (item.children && item.children.length > 0) {
                changedChildren = deepFirstChange(item.children)
            }
            if (permissionList.includes(item.value) || isAdmin) {//如果包含权限的话，就返回
                if (item.type === "1") {
                    return {
                        path: item.value,
                        name: item.label,
                        children: changedChildren
                    }
                } else if (item.type === "2") {
                    return {
                        path: item.value,
                        name: item.label,
                        children: []
                    }
                }
            }
        })?.filter(el => el)//filter过滤掉undefined
        return res
    }
    let result = deepFirstChange(allMenus)?.filter(item => item)
    return result;
}

//生成随机颜色
export function genRandomColor() {
    let r = Math.round(Math.random() * 255)
    let g = Math.round(Math.random() * 255)
    let b = Math.round(Math.random() * 255)
    return `rgb(${r},${g},${b})`
}
//导出pdf
export function ExportSavePdf(name, id) {
    var element = document.getElementById(id)
    // window.scrollTo(0, $(this).offset().top);//最为关键的地方 需要滚动到指定标签  否则图片不全
    html2canvas(element, {
        logging: false
    }).then(function (canvas) {
        var pdf = new JSPDF('p', 'mm', 'a4') // A4纸，纵向
        var ctx = canvas.getContext('2d')
        var a4w = 170;
        var a4h = 257 // A4大小，210mm x 297mm，四边各保留20mm的边距，显示区域170x257
        var imgHeight = Math.floor(a4h * canvas.width / a4w) // 按A4显示比例换算一页图像的像素高度
        var renderedHeight = 0
        while (renderedHeight < canvas.height) {
            var page = document.createElement('canvas')
            page.width = canvas.width
            page.height = Math.min(imgHeight, canvas.height - renderedHeight) // 可能内容不足一页
            // 用getImageData剪裁指定区域，并画到前面创建的canvas对象中
            page.getContext('2d').putImageData(ctx.getImageData(0, renderedHeight, canvas.width, Math.min(imgHeight, canvas.height - renderedHeight)), 0, 0)
            pdf.addImage(page.toDataURL('image/jpeg', 1.0), 'JPEG', 10, 10, a4w, Math.min(a4h, a4w * page.height / page.width)) // 添加图像到页面，保留10mm边距
            renderedHeight += imgHeight
            if (renderedHeight < canvas.height) {
                pdf.addPage()
            } // 如果后面还有内容，添加一个空页
            // delete page;
        }
        pdf.save(name)
    })
}
//从字典里value=>>label
export function getLabelFromDic(value, setName) {
    return $store.state.sysParamsData.filter(item => item.setname == setName)?.find(item => item.code === value)?.name || value
}
// 本日本月本年毫秒级时间戳
export function timeFrame(val) {
    const now = new Date();
    let nowDay = now.getDate(); //当前日 
    let nowMonth = now.getMonth(); //当前月 
    let nowYear = now.getFullYear(); //当前年 


    let startOfDay = new Date(nowYear, nowMonth, nowDay);
    let endOfDay = new Date(nowYear, nowMonth, nowDay + 1);



    let startOfMonth = new Date(nowYear, nowMonth, 1)
    let endOfMonth = new Date(nowYear, nowMonth + 1, 1)


    let startOfYear = new Date(nowYear, 0, 1)
    let endOfYear = new Date(nowYear + 1, 0, 1)


    let startTimestamp = null
    let endTimestamp = null
    switch (val) {
        case 'day':
            startTimestamp = startOfDay.getTime();
            endTimestamp = endOfDay.getTime() - 1;
            break;
        case 'month':
            startTimestamp = startOfMonth.getTime();
            endTimestamp = endOfMonth.getTime() - 1;
            break;
        case 'year':
            startTimestamp = startOfYear.getTime();
            endTimestamp = endOfYear.getTime() - 1;
            break;

        default:
            break;
    }
    return [startTimestamp, endTimestamp]
}

export function timestampToTime(timestamp) {
    timestamp = timestamp ? timestamp : null;
    let date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
    let Y = date.getFullYear() + '-';
    let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
    let h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
    let m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
    let s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
    return Y + M + D + h + m + s;
}
export function timeToTimestamp(time) {
    let timestamp = Date.parse(new Date(time).toString());
    //timestamp = timestamp / 1000; //时间戳为13位需除1000，时间戳为13位的话不需除1000
    // console.log(time + "的时间戳为：" + timestamp);
    return timestamp;
    //2021-11-18 22:14:24的时间戳为：1637244864707
}

/**
 * 打开一个窗口(二次封装el-message-box)
 * @param {*} options 配置项
 * @param {*} options.component 弹框要包容的组件
 * @param {*} options.props 弹框中父传子的props以及监听方法
 * @param {*} options.title 弹框中标题,如果不传,那么是'数据详情'
 * @param {*} options.otherOptions 参数参考https://element-plus.gitee.io/zh-CN/component/message-box.html#配置项
 * @example 
 * opendialog({
    component:Helloworld,
    props:(closeDialog)=>{
        return {
            formData:{name:'zs'},
            onRefresh:(data)=>{
                closeDialog()
            }
        }
    },
    title:"数据详情",
    otherOptions:{
        customStyle:{
            width:'80%',
            maxWidth:'100%',
        }
    }
})
 */
export function openDialog(options) {
    debugger
    //1.解构参数
    const { component,props:getPropsFunc=()=>{},title='数据详情',otherOptions={} } = options
    //2.打开弹框
    ElMessageBox({
        customStyle:{//默认样式
            width:'60%',
            maxWidth:'100%',
        },
        title: title,
        message: () =>{
            return h(component, getPropsFunc(ElMessageBox.close))
        },
        showConfirmButton:false,//不显示确定按钮
        ...otherOptions
    })
}
